package com.r2coding.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.r2coding.common.constant.Constant;
import com.r2coding.common.enums.EmailType;
import com.r2coding.common.exception.BizCode;
import com.r2coding.common.exception.ServiceException;
import com.r2coding.system.dao.UserDao;
import com.r2coding.system.entity.UserEntity;
import com.r2coding.system.feign.ThirdPartyFeignService;
import com.r2coding.system.model.SystemEmailReq;
import com.r2coding.system.vo.req.QueryOpinionReqVo;
import com.r2coding.system.vo.resp.OpinionRespVo;
import com.r2coding.system.vo.resp.OpinionResponseVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.r2coding.common.util.PageUtils;
import com.r2coding.common.util.Result;
import com.r2coding.common.util.Query;

import com.r2coding.system.dao.OpinionDao;
import com.r2coding.system.entity.OpinionEntity;
import com.r2coding.system.service.OpinionService;
import org.springframework.util.CollectionUtils;

/**
 * 用户意见
 *
 * @author 98k灬
 * @email hk666zx@163.com
 * @date 2022-08-12 13:00:08
 */
@Service("opinionService")
public class OpinionServiceImpl extends ServiceImpl<OpinionDao, OpinionEntity> implements OpinionService {



    @Autowired
    UserDao userDao;

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OpinionEntity> page = this.page(
                new Query<OpinionEntity>().getPage(params),
                new QueryWrapper<OpinionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateOpinion(OpinionEntity opinion) {
        OpinionEntity opinionEntity = this.baseMapper.selectById(opinion.getId());
        if (opinionEntity == null) {
            throw new ServiceException(BizCode.INVALID_PARAM);
        }

        if (opinion.getIsNotice() == 1) {
            sendEmail(opinionEntity);
        }
        opinion.setIsHandle(1);
        opinion.setHandleTime(new Date());
        this.baseMapper.updateById(opinion);
    }

    public void sendEmail(OpinionEntity opinion) {
        SystemEmailReq req = new SystemEmailReq();
        req.setEmail(opinion.getEmail());
        req.setEmailType(EmailType.OPINION_USER);
        thirdPartyFeignService.sendSystemEmail(req);
    }

    @Override
    public OpinionResponseVo listOpinion(QueryOpinionReqVo req) {
        OpinionResponseVo responseVo = new OpinionResponseVo();
        QueryWrapper<OpinionEntity> wrapper = new QueryWrapper<>();
        if (req.getIsHandle() != null) {
            wrapper.eq("is_handle", req.getIsHandle());
        }
        if (req.getType() != null) {
            wrapper.eq("type", req.getType());
        }
        wrapper.orderByDesc("create_time");
        Integer count = this.baseMapper.selectCount(wrapper);
        responseVo.setTotal(count);

        PageHelper.startPage(req.getCurrent(), req.getSize());
        List<OpinionEntity> list = this.baseMapper.selectList(wrapper);
        List<OpinionRespVo> collect = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            collect = list.stream().map(item -> {
                // 根据用户id查询用户信息
                OpinionRespVo vo = new OpinionRespVo();
                BeanUtils.copyProperties(item, vo);
                if (item.getUserId() != null) {
                    UserEntity user = userDao.selectById(item.getUserId());
                    vo.setUserName(user.getUserName());
                }
                return vo;
            }).collect(Collectors.toList());
        }
        responseVo.setList(collect);
        return responseVo;
    }

    @Override
    public void saveOpinion(OpinionEntity opinion) {
        // TODO 同一个用户一天只能提交一次
        Integer userId = 0;
        try {
            // 获取用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
            Map<String, Object> map = (Map<String, Object>)details.getDecodedDetails();
            Map<String, Object> userInfo = (Map<String, Object>)map.get("userInfo");
            userId = (Integer)userInfo.get("userId");
        } catch( Exception exception ) {
            log.error(exception.getMessage());
        }
        opinion.setUserId(userId > 0 ? userId : null);
        opinion.setIsDelete(0);
        opinion.setCreateTime(new Date());
        opinion.setUpdateTime(new Date());
        opinion.setIsHandle(0);
        this.baseMapper.insert(opinion);
        sendOpinionAdminEmail();
    }

    @Async
    public void sendOpinionAdminEmail() {
        SystemEmailReq req = new SystemEmailReq();
        req.setEmail(Constant.ADMIN_EMAIL);
        req.setEmailType(EmailType.OPINION_ADMIN);
        thirdPartyFeignService.sendSystemEmail(req);
    }
}